<?php

class FilesModel extends myAcicrud {
    public function __construct($table = null, $database = null) {
        parent::__construct('files');
        
        $this->toJoinAkumTables = array('fcs' => 'files_classroom_subject', 'fl' => 'files_language', 'fpo' => 'files_program_os', 'fsl' => 'files_study_level', 'fwt' => 'files_work_type');
        $this->toJoinCategoryTables = array('cs' => 'classroom_subject', 'l' => 'language', 'po' => 'program_os', 'sl' => 'study_level', 'wt' => 'work_type');
        $this->ITEMS_ON_PAGE = 10;
    }
    
    public function getPageCount($where = null)   
    {
    	$this->db->select('');
        $this->db->from("$this->table f");
        
        foreach($this->toJoinAkumTables as $key => $table){
            $this->db->join("$table $key", "f.id = $key.fk_files");
        }
        foreach($this->toJoinCategoryTables as $key => $table){
            $this->db->join("$table $key", "f$key.fk_$table = $key.id");
        }
        
        foreach($where as $key => $value){
            $this->db->where("$key.id", $value);
        }
        
        $this->o_db->group_by("f.id");
    	
        $count = count($this->result());
        return ceil($count / $this->ITEMS_ON_PAGE);
    } 
    
    public function getAllFiles(array $filter, array $orderBy, $page) {
        $select = $this->generateSelectedItems();
        
        $this->db->select($select);
        $this->db->from("$this->table f");
        
        foreach($this->toJoinAkumTables as $key => $table){
            $this->db->join("$table $key", "f.id = $key.fk_files");
        }
        foreach($this->toJoinCategoryTables as $key => $table){
            $this->db->join("$table $key", "f$key.fk_$table = $key.id");
        }
        
        foreach($filter as $key => $value){
            $this->db->where("$key.id", $value);
        }
        
        $this->o_db->order_by("f.id", "ASC");
        
        foreach($orderBy as $key => $order){
            $this->o_db->order_by($key, $order);
        }
        
        $this->o_db->group_by("f.id");
        
        $this->o_db->limit($this->ITEMS_ON_PAGE, $page * $this->ITEMS_ON_PAGE);

        return $this->result();
    }
    
    private function generateSelectedItems() {
        $result = "f.id id, f.name name, f.comment comment, f.autors autors, f.size size, f.requirements requirements, f.time time";
        
        /*foreach($this->toJoinCategoryTables as $key => $table){
            $result .= ", $key.name $key"."_name";
        }*/
        
        return $result;
    }
    
}

?>
